<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="租客姓名" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入租客姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租客手机号" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入租客手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间" prop="roomId">
        <el-input
          v-model="queryParams.roomId"
          placeholder="请输入房间"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startDate">
        <el-date-picker clearable
                        v-model="queryParams.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endDate">
        <el-date-picker clearable
                        v-model="queryParams.endDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethodId">
        <el-select v-model="queryParams.paymentMethodId" placeholder="请选择支付方式" clearable>
          <el-option
            v-for="item in paymentMethodOptions"
            :key="item.paymentMethodId"
            :label="item.paymentMethod"
            :value="item.paymentMethodId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="可选租期" prop="rentalPeriodId">
        <el-select v-model="queryParams.rentalPeriodId" placeholder="请选择租期" clearable>
          <el-option
            v-for="item in rentalPeriodOptions"
            :key="item.rentalPeriodId"
            :label="item.rentalPeriod"
            :value="item.rentalPeriodId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租金" prop="rent">
        <el-input
          v-model="queryParams.rent"
          placeholder="请输入租金"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="押金" prop="deposit">
        <el-input
          v-model="queryParams.deposit"
          placeholder="请输入押金"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['leases:leases:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['leases:leases:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['leases:leases:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['leases:leases:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leasesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="leaseId" />
      <el-table-column label="租客姓名" align="center" prop="tenantName" />
      <el-table-column label="租客手机号" align="center" prop="phoneNumber" />
      <el-table-column label="房间" align="center" prop="roomId" />
      <el-table-column label="开始时间" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['leases:leases:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['leases:leases:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改租约管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="租客姓名" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入租客姓名" />
        </el-form-item>
        <el-form-item label="租客手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入租客手机号" />
        </el-form-item>
        <el-form-item label="身份证号码" prop="idCardNumber">
          <el-input v-model="form.idCardNumber" placeholder="请输入身份证号码" />
        </el-form-item>
        <el-form-item label="房间" prop="roomId">
          <el-input v-model="form.roomId" placeholder="请输入房间" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker clearable
                          v-model="form.startDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker clearable
                          v-model="form.endDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethodId">
          <el-select v-model="form.paymentMethodId" placeholder="请选择支付方式">
            <el-option
              v-for="item in paymentMethodOptions"
              :key="item.paymentMethodId"
              :label="item.paymentMethod"
              :value="item.paymentMethodId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可选租期" prop="rentalPeriodId">
          <el-select v-model="form.rentalPeriodId" placeholder="请选择租期">
            <el-option
              v-for="item in rentalPeriodOptions"
              :key="item.rentalPeriodId"
              :label="item.rentalPeriod"
              :value="item.rentalPeriodId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="租金" prop="rent">
          <el-input-number
            v-model="form.rent"
            :min="0"
            :precision="2"
            :step="100"
            :step-strictly="true"
            controls-position="right"
            placeholder="请输入租金"
          />
        </el-form-item>
        <el-form-item label="押金" prop="deposit">
          <el-input-number
            v-model="form.deposit"
            :min="0"
            :precision="2"
            :step="100"
            :step-strictly="true"
            controls-position="right"
            placeholder="请输入押金"
          />
        </el-form-item>
        <el-form-item label="备注信息" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="租客" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="请选择租客">
            <el-option
              v-for="item in tenantOptions"
              :key="item.tenantId"
              :label="item.nickName"
              :value="item.tenantId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="户主" prop="homeownerId">
          <el-select v-model="form.homeownerId" placeholder="请选择户主">
            <el-option
              v-for="item in homeownerOptions"
              :key="item.homeownerId"
              :label="item.nickName"
              :value="item.homeownerId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLeases, getLeases, delLeases, addLeases, updateLeases } from "@/api/leases/leases";
import { listMethods } from "@/api/methods/methods";
import { listPeriod } from "@/api/period/period";
import { listHomeowners } from "@/api/homeowners/homeowners";
import { listTenants } from "@/api/tenants/tenants";

export default {
  name: "Leases",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租约管理表格数据
      leasesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantName: null,
        phoneNumber: null,
        idCardNumber: null,
        roomId: null,
        startDate: null,
        endDate: null,
        paymentMethodId: undefined,
        rentalPeriodId: undefined,
        rent: null,
        deposit: null,
        notes: null,
        tenantId: undefined,
        homeownerId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenantName: [
          { required: true, message: "租客姓名不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "租客手机号不能为空", trigger: "blur" }
        ],
        idCardNumber: [
          { required: true, message: "身份证号码不能为空", trigger: "blur" }
        ],
        roomId: [
          { required: true, message: "房间不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        paymentMethodId: [
          { required: true, message: "支付方式不能为空", trigger: "blur" }
        ],
        rentalPeriodId: [
          { required: true, message: "可选租期不能为空", trigger: "blur" }
        ],
        rent: [
          { required: true, message: "租金不能为空", trigger: "blur" },
          { type: 'number', message: "租金必须为数字", trigger: "blur" }
        ],
        deposit: [
          { required: true, message: "押金不能为空", trigger: "blur" },
          { type: 'number', message: "押金必须为数字", trigger: "blur" }
        ],
        tenantId: [
          { required: true, message: "租客id不能为空", trigger: "blur" }
        ],
        homeownerId: [
          { required: true, message: "户主id不能为空", trigger: "blur" }
        ]
      },
      paymentMethodOptions: [],
      rentalPeriodOptions: [],
      tenantOptions: [],
      homeownerOptions: [],
    };
  },
  created() {
    this.getList();
    this.getPaymentMethods();
    this.getRentalPeriods();
    this.getTenants();
    this.getHomeowners();
  },
  methods: {
    /** 查询租约管理列表 */
    getList() {
      this.loading = true;
      // listLeases(this.queryParams).then(response => {
      //   this.leasesList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
      listLeases(this.queryParams).then(response => {
        this.leasesList = response.rows.map(lease => ({
          ...lease,
            nickName: this.getNickNameById(lease.tenantId)
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    getNickNameById(tenantId) {
      const tenant = this.tenantOptions.find(item => item.tenantId === tenantId);
      return tenant ? tenant.nickName : '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        leaseId: null,
        tenantName: null,
        phoneNumber: null,
        idCardNumber: null,
        roomId: null,
        startDate: null,
        endDate: null,
        paymentMethodId: undefined,
        rentalPeriodId: undefined,
        rent: null,
        deposit: null,
        notes: null,
        tenantId: undefined,
        homeownerId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.leaseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加租约管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const leaseId = row.leaseId || this.ids
      getLeases(leaseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改租约管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.leaseId != null) {
            updateLeases(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLeases(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const leaseIds = row.leaseId || this.ids;
      this.$modal.confirm('是否确认删除租约管理编号为"' + leaseIds + '"的数据项？').then(function () {
        return delLeases(leaseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('leases/leases/export', {
        ...this.queryParams
      }, `leases_${new Date().getTime()}.xlsx`)
    },
    /** 获取支付方式列表 */
    getPaymentMethods() {
      listMethods().then(response => {
        this.paymentMethodOptions = response.rows;
      });
    },
    /** 获取可选租期列表 */
    getRentalPeriods() {
      listPeriod().then(response => {
        this.rentalPeriodOptions = response.rows;
      });
    },
    /** 获取租客列表 */
    getTenants() {
      listTenants().then(response => {
        this.tenantOptions = response.rows;
      });
    },
    /** 获取户主列表 */
    getHomeowners() {
      listHomeowners().then(response => {
        this.homeownerOptions = response.rows;
      });
    },
  }
};
</script>
